from django.contrib.auth.hashers import make_password, check_password
from django.db.models import Q
from rest_framework.views import APIView
from rest_framework.response import Response
from myapp.models import User

import re

# 用户注册
class Register(APIView):
    def get(self, request):
        # 接收参数
        username = request.GET.get('username', None)
        password = request.GET.get('password', None)
        pwd = request.GET.get('pwd', None)
        phone = request.GET.get('phone', None)
        password2 = make_password(password)

        if not all([username, password, pwd, phone]):
            return Response({'msg': '请填写完整数据后提交！', 'code': 400})

        # 排重
        user = User.objects.filter(username=username).first()
        if user:
            res = {}
            res['code'] = 405
            res['msg'] = '用户已经存在'
            return Response(res)

        if password != pwd:
            return Response({'msg': '两次密码不一致', 'code': 400})

        phone_re = re.compile(r'^1(3\d|4[4-9]|5[0-35-9]|6[67]|7[013-8]|8[0-9]|9[0-9])\d{8}$')
        if not re.search(phone_re, phone):
            return Response({'msg': '手机号不符合规范', 'code': 400})

        # 入库
        user = User(username=username, password=password2, phone=phone)
        user.save()
        return Response({'msg': '注册成功', 'code': 200})


# 用户登录
class Login(APIView):
    def get(self, request):
        # 获取数据
        username = request.GET.get('username', None)
        password = request.GET.get('password', None)

        # 检查数据
        user_obj = User.objects.filter(Q(username=username) | Q(phone=username)).first()

        if user_obj:
            pwd = check_password(password, user_obj.password)
            if pwd == True:
                return Response({'msg': '登录成功', 'code': 200})
            else:
                return Response({'msg': '用户名或密码错误', 'code': 400})
        else:
            return Response({'msg': '用户不存在', 'code': 400})







